// pages/custom-category/custom-category.js
Page({
  data: {
    categoryName: '',
    selectedIcon: '',
    canSave: false,
    savedCategories: [], // 已保存的自定义类别
    hiddenCategories: [], // 已隐藏的默认类别
    showEditModal: false, // 控制是否显示编辑弹窗
    showAddModal: false,
    currentTab: 'expense', // 当前选择的标签页：expense(支出) 或 income(收入)
    // 图标数据
    jiaotongIcons: [
      'a-busgongjiaochegonggongqichekechejiaotonggongju.png',
      'a-ditiejiaotonggongju.png',
      'a-taxichuzucheqichexiaochejiaotonggongju.png',
      'jiaotonggongju1.png',
      'jiaotonggongju2.png',
      'jiaotonggongju4.png',
      'jiaotong.png'
    ],
    yinshiIcons: [
      'Pear.png',
      'a-2-58.png',
      'chicken-meat.png',
      'shiwuqimin.png',
      'shiwuqimin_1.png',
      'food.png'
    ],
    yuleIcons: [
      '-yule.png',
      'ertongyule.png',
      'tiyu.png',
      'yule3.png',
      'yule_1.png',
      'yule_2.png',
      'lvyou.png',
      'yule.png'
    ],
    shenghuoIcons: [
      'fushilei.png',
      'housing.png',
      'meirong.png',
      'tongxun.png'
    ],
    shouruIcons: [
      'jiage.png',
      'qian.png',
      'qianbi.png',
      'rp1.png',
      'shourulaiyuanguanli.png',
      'zongbaoe.png'
    ]
  },

  onLoad(options) {
    // 页面加载时的初始化
    // 根据来源页面设置默认标签页
    if (options.type) {
      this.setData({
        currentTab: options.type === 'income' ? 'income' : 'expense'
      });
    }
    this.loadSavedCategories();
  },

  // 关闭弹窗
  closeModal() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 输入类别名称
  onNameInput(e) {
    const value = e.detail.value || e.detail;
    console.log('输入类别名称:', value);
    this.setData({
      categoryName: value
    });
    this.checkCanSave();
  },

  // 选择图标
  selectIcon(e) {
    const icon = e.currentTarget.dataset.icon;
    console.log('选择图标:', icon);
    this.setData({
      selectedIcon: icon
    });
    this.checkCanSave();
  },

  // 检查是否可以保存
  checkCanSave() {
    const { categoryName, selectedIcon } = this.data;
    // 检查名称长度（2-4个汉字）
    const nameValid = this.validateCategoryName(categoryName);
    const iconSelected = selectedIcon !== '';
    
    console.log('checkCanSave - 类别名称:', categoryName, '名称有效:', nameValid, '图标已选择:', iconSelected);
    
    this.setData({
      canSave: nameValid && iconSelected
    });
    
    console.log('canSave状态更新为:', nameValid && iconSelected);
  },

  // 验证类别名称
  validateCategoryName(name) {
    if (!name) return false;
    // 只检查名称不为空，移除字数和字符类型限制
    return name.trim().length > 0;
  },

  // 检查名称是否重复
  checkNameDuplicate(name) {
    // 获取现有的自定义类别
    const customCategories = wx.getStorageSync('customCategories') || [];
    return customCategories.some(category => category.name === name);
  },

  // 保存类别
  saveCategory(e) {
    console.log('saveCategory方法被调用');
    console.log('点击事件对象:', e);
    console.log('canSave状态:', this.data.canSave);
    console.log('当前时间:', new Date().toLocaleTimeString());
    
    // 检查是否可以保存
    if (!this.data.canSave) {
      console.log('canSave为false，直接返回');
      return;
    }
    
    const { categoryName, selectedIcon } = this.data;
    console.log('类别名称:', categoryName, '选择的图标:', selectedIcon);
    
    // 再次验证
    if (!this.validateCategoryName(categoryName)) {
      wx.showToast({
        title: '请输入类别名称',
        icon: 'none'
      });
      return;
    }

    if (!selectedIcon) {
      wx.showToast({
        title: '请选择图标',
        icon: 'none'
      });
      return;
    }

    // 检查名称重复
    if (this.checkNameDuplicate(categoryName)) {
      wx.showToast({
        title: '该类别已存在',
        icon: 'none'
      });
      return;
    }

    // 保存到本地存储
    const customCategories = wx.getStorageSync('customCategories') || [];
    const { currentTab } = this.data;
    const newCategory = {
      id: Date.now(), // 使用时间戳作为ID
      name: categoryName,
      icon: selectedIcon,
      type: currentTab, // 添加类型字段
      createTime: new Date().toISOString()
    };
    
    customCategories.push(newCategory);
    wx.setStorageSync('customCategories', customCategories);
    console.log('类别已保存到本地存储:', newCategory);

    // 显示成功提示
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });
    console.log('显示保存成功提示');

    // 重新加载已保存的类别
    this.loadSavedCategories();
    
    // 保存成功后关闭弹窗并重置表单
    this.setData({
      categoryName: '',
      selectedIcon: '',
      canSave: false,
      showAddModal: false
    });

    // 通知record页面刷新类别数据
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; // 获取上一个页面
    if (prevPage && prevPage.route === 'pages/record/record') {
      prevPage.loadCustomCategories(); // 调用上一个页面的刷新方法
    }
  },

  // 加载已保存的自定义类别
  loadSavedCategories() {
    const customCategories = wx.getStorageSync('customCategories') || [];
    const defaultCategories = this.getDefaultCategories();
    const hiddenCategoryIds = wx.getStorageSync('hiddenCategories') || [];
    const { currentTab } = this.data;
    
    // 获取隐藏的类别详情
    const hiddenCategories = this.getHiddenCategoriesDetails(hiddenCategoryIds);
    
    // 过滤自定义类别，只显示当前标签页对应的类别
    const filteredCustomCategories = customCategories.filter(category => {
      return category.type === currentTab;
    });
    
    // 合并自定义类别和默认类别
    const allCategories = [
      ...defaultCategories,
      ...filteredCustomCategories.map(category => ({
        ...category,
        iconPath: this.getCustomIconPath(category.icon),
        isCustom: true
      }))
    ];
    
    this.setData({
      savedCategories: allCategories,
      hiddenCategories: hiddenCategories
    });
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
    // 重新加载类别数据
    this.loadSavedCategories();
  },
  
  // 滑动切换
  swiperChange(e) {
    const current = e.detail.current;
    const tab = current === 0 ? 'expense' : 'income';
    this.setData({
      currentTab: tab
    });
    // 重新加载类别数据
    this.loadSavedCategories();
  },

  // 获取默认类别数据
  getDefaultCategories() {
    const hiddenCategories = wx.getStorageSync('hiddenCategories') || [];
    const { currentTab } = this.data;
    
    // 支出类别
    const expenseCategories = [
      { id: 'default_1', name: '餐饮', icon: 'food.png', iconPath: '../../icon/food.png', isCustom: false, type: 'expense' },
      { id: 'default_2', name: '交通', icon: 'jiaotong.png', iconPath: '../../icon/jiaotong.png', isCustom: false, type: 'expense' },
      { id: 'default_3', name: '住房', icon: 'housing.png', iconPath: '../../icon/housing.png', isCustom: false, type: 'expense' },
      { id: 'default_4', name: '美容', icon: 'meirong.png', iconPath: '../../icon/meirong.png', isCustom: false, type: 'expense' },
      { id: 'default_5', name: '服装', icon: 'fushilei.png', iconPath: '../../icon/fushilei.png', isCustom: false, type: 'expense' },
      { id: 'default_6', name: '旅游', icon: 'lvyou.png', iconPath: '../../icon/lvyou.png', isCustom: false, type: 'expense' },
      { id: 'default_7', name: '娱乐', icon: 'yule.png', iconPath: '../../icon/yule.png', isCustom: false, type: 'expense' },
      { id: 'default_8', name: '医疗', icon: 'yiliao.png', iconPath: '../../icon/yiliao.png', isCustom: false, type: 'expense' },
      { id: 'default_9', name: '通讯', icon: 'tongxun.png', iconPath: '../../icon/tongxun.png', isCustom: false, type: 'expense' },
      { id: 'default_10', name: '学习', icon: 'xuexi.png', iconPath: '../../icon/xuexi.png', isCustom: false, type: 'expense' },
      { id: 'default_11', name: '数码', icon: 'shumapeijian.png', iconPath: '../../icon/shumapeijian.png', isCustom: false, type: 'expense' },
      { id: 'default_12', name: '其他', icon: 'qita.png', iconPath: '../../icon/qita.png', isCustom: false, type: 'expense' }
    ];
    
    // 收入类别
    const incomeCategories = [
      { id: 'income_1', name: '工资', icon: 'gongzi.png', iconPath: '../../icon/gongzi.png', isCustom: false, type: 'income' },
      { id: 'income_2', name: '奖金', icon: 'jiangjin.png', iconPath: '../../icon/jiangjin.png', isCustom: false, type: 'income' },
      { id: 'income_3', name: '兼职', icon: 'jianzhi.png', iconPath: '../../icon/jianzhi.png', isCustom: false, type: 'income' },
      { id: 'income_4', name: '理财', icon: 'lijin.png', iconPath: '../../icon/lijin.png', isCustom: false, type: 'income' }
    ];
    
    // 根据当前标签页选择对应的类别
    const allDefaultCategories = currentTab === 'expense' ? expenseCategories : incomeCategories;
    
    // 过滤掉已隐藏的类别
    return allDefaultCategories.filter(category => !hiddenCategories.includes(category.id));
  },

  // 获取自定义图标路径
  getCustomIconPath(iconName) {
    const { jiaotongIcons, yinshiIcons, yuleIcons, shenghuoIcons, shouruIcons } = this.data;
    
    if (jiaotongIcons.includes(iconName)) {
      return `/icon/images/jiaotong/${iconName}`;
    } else if (yinshiIcons.includes(iconName)) {
      return `/icon/images/yinshi/${iconName}`;
    } else if (yuleIcons.includes(iconName)) {
      return `/icon/images/yule/${iconName}`;
    } else if (shenghuoIcons.includes(iconName)) {
      return `/icon/images/shenghuo/${iconName}`;
    } else if (shouruIcons.includes(iconName)) {
      return `/icon/images/shouru/${iconName}`;
    }
    
    return `/icon/images/qita/${iconName}`; // 默认路径
  },

  // 删除类别
  deleteCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    const category = this.data.savedCategories.find(cat => cat.id === categoryId);
    
    if (!category) return;
    
    const isCustom = category.isCustom;
    const title = '删除类别';
    const content = isCustom ? '确定要删除这个自定义类别吗？删除后无法恢复。' : '确定要删除这个默认类别吗？删除后无法恢复。';
    
    wx.showModal({
      title: title,
      content: content,
      success: (res) => {
        if (res.confirm) {
          if (isCustom) {
            // 删除自定义类别
            let customCategories = wx.getStorageSync('customCategories') || [];
            customCategories = customCategories.filter(cat => cat.id !== categoryId);
            wx.setStorageSync('customCategories', customCategories);
          } else {
            // 删除默认类别（添加到隐藏列表中实现删除效果）
            let hiddenCategories = wx.getStorageSync('hiddenCategories') || [];
            if (!hiddenCategories.includes(categoryId)) {
              hiddenCategories.push(categoryId);
              wx.setStorageSync('hiddenCategories', hiddenCategories);
            }
          }
          
          // 重新加载已保存的类别
          this.loadSavedCategories();
          
          // 通知record页面刷新数据
          const pages = getCurrentPages();
          const recordPage = pages.find(page => page.route === 'pages/record/record');
          if (recordPage) {
            recordPage.loadCustomCategories();
          }
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 获取隐藏类别的详细信息
  getHiddenCategoriesDetails(hiddenCategoryIds) {
    const { currentTab } = this.data;
    
    // 支出类别
    const expenseCategories = [
      { id: 'default_1', name: '餐饮', icon: '../../icon/food.png', type: 'expense' },
      { id: 'default_2', name: '交通', icon: '../../icon/jiaotong.png', type: 'expense' },
      { id: 'default_3', name: '住房', icon: '../../icon/housing.png', type: 'expense' },
      { id: 'default_4', name: '美容', icon: '../../icon/meirong.png', type: 'expense' },
      { id: 'default_5', name: '服装', icon: '../../icon/fushilei.png', type: 'expense' },
      { id: 'default_6', name: '旅游', icon: '../../icon/lvyou.png', type: 'expense' },
      { id: 'default_7', name: '娱乐', icon: '../../icon/yule.png', type: 'expense' },
      { id: 'default_8', name: '医疗', icon: '../../icon/yiliao.png', type: 'expense' },
      { id: 'default_9', name: '通讯', icon: '../../icon/tongxun.png', type: 'expense' },
      { id: 'default_10', name: '学习', icon: '../../icon/xuexi.png', type: 'expense' },
      { id: 'default_11', name: '数码', icon: '../../icon/shumapeijian.png', type: 'expense' },
      { id: 'default_12', name: '其他', icon: '../../icon/qita.png', type: 'expense' }
    ];
    
    // 收入类别
    const incomeCategories = [
      { id: 'income_1', name: '工资', icon: '../../icon/gongzi.png', type: 'income' },
      { id: 'income_2', name: '奖金', icon: '../../icon/jiangjin.png', type: 'income' },
      { id: 'income_3', name: '兼职', icon: '../../icon/jianzhi.png', type: 'income' },
      { id: 'income_4', name: '理财', icon: '../../icon/lijin.png', type: 'income' }
    ];
    
    // 根据当前标签页选择对应的类别
    const allDefaultCategories = currentTab === 'expense' ? expenseCategories : incomeCategories;
    
    return allDefaultCategories
      .filter(category => hiddenCategoryIds.includes(category.id))
      .map(category => ({
        ...category,
        iconPath: category.icon
      }));
  },

  // 恢复隐藏的类别
  restoreCategory(e) {
    const categoryId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '恢复类别',
      content: '确定要恢复这个类别吗？',
      success: (res) => {
        if (res.confirm) {
          // 从隐藏列表中移除
          let hiddenCategories = wx.getStorageSync('hiddenCategories') || [];
          hiddenCategories = hiddenCategories.filter(id => id !== categoryId);
          wx.setStorageSync('hiddenCategories', hiddenCategories);
          
          // 重新加载数据
          this.loadSavedCategories();
          
          // 通知record页面刷新数据
          const pages = getCurrentPages();
          const recordPage = pages.find(page => page.route === 'pages/record/record');
          if (recordPage) {
            recordPage.loadCustomCategories();
          }
          
          wx.showToast({
            title: '恢复成功',
            icon: 'success'
          });
        }
      }
    });
  },

  openAddModal() {
    this.setData({
      showAddModal: true
    });
  },

  closeAddModal() {
    this.setData({
      showAddModal: false,
      categoryName: '',
      selectedIcon: ''
    });
  }
});